<template>
  <a-modal
    v-model:open="modalOpen"
    title="用户注册"
    :width="500"
    :closable="true"
    :mask-closable="true"
    :mask="true"
    :z-index="1000"
    :centered="true"
    @cancel="handleCancel"
    @ok="handleCancel"
  >
    <div class="register-container">
      <div class="register-header">
        <h1>智教易购平台</h1>
        <p>用户注册 - 加入我们的学习社区</p>
      </div>

      <a-form
        :model="formData"
        :rules="rules"
        @finish="handleRegister"
        class="register-form"
        layout="vertical"
      >
        <!-- 基本信息 -->
        <a-form-item label="用户名" name="username">
          <a-input
            v-model:value="formData.username"
            size="large"
            placeholder="请输入用户名"
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="手机号" name="phone">
          <a-input
            v-model:value="formData.phone"
            size="large"
            placeholder="请输入手机号"
          >
            <template #prefix>
              <PhoneOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="邮箱" name="email">
          <a-input
            v-model:value="formData.email"
            size="large"
            placeholder="请输入邮箱地址"
          >
            <template #prefix>
              <MailOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="密码" name="password">
          <a-input-password
            v-model:value="formData.password"
            size="large"
            placeholder="请输入密码（至少6位）"
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item label="确认密码" name="confirmPassword">
          <a-input-password
            v-model:value="formData.confirmPassword"
            size="large"
            placeholder="请再次输入密码"
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <!-- 验证码 -->
        <a-form-item label="验证码" name="captcha">
          <div class="captcha-container">
            <a-input
              v-model:value="formData.captcha"
              size="large"
              placeholder="请输入验证码"
              style="flex: 1; margin-right: 12px;"
            >
              <template #prefix>
                <SafetyOutlined />
              </template>
            </a-input>
            <div class="captcha-image" @click="refreshCaptcha">
              <img v-if="captchaImage" :src="captchaImage" alt="验证码" />
              <div v-else class="captcha-placeholder">点击获取验证码</div>
            </div>
          </div>
        </a-form-item>

        <!-- 用户协议 -->
        <a-form-item name="agreement">
          <a-checkbox v-model:checked="formData.agreement">
            我已阅读并同意
            <a-button type="link" class="agreement-link">《用户协议》</a-button>
            和
            <a-button type="link" class="agreement-link">《隐私政策》</a-button>
          </a-checkbox>
        </a-form-item>

        <!-- 注册按钮 -->
        <a-form-item>
          <a-button
            type="primary"
            size="large"
            block
            class="register-btn"
            @click="handleRegister"
            :loading="registerLoading"
          >
            立即注册
          </a-button>
        </a-form-item>
      </a-form>

      <!-- 登录链接 -->
      <div class="login-section">
        <span>已有账号？</span>
        <a-button type="link" @click="goToLogin">
          立即登录
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useAuthStore } from '@/stores/authStore'
import { message } from 'ant-design-vue'
import { register, getCaptcha } from '@/api/user/authController'
import {
  UserOutlined,
  MailOutlined,
  LockOutlined,
  PhoneOutlined,
  SafetyOutlined
} from '@ant-design/icons-vue'

interface Props {
  open: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'register-success', user: any): void
  (e: 'show-login'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 计算属性用于v-model:open
const modalOpen = computed({
  get: () => props.open,
  set: (value: boolean) => emit('update:open', value)
})

const authStore = useAuthStore()

// 表单数据
const formData = reactive({
  username: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  captchaKey: '',
  agreement: false
})

// 验证码相关
const captchaImage = ref('')

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string) => {
        if (value !== formData.password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  agreement: [
    {
      validator: (rule: any, value: boolean) => {
        if (!value) {
          return Promise.reject('请阅读并同意用户协议和隐私政策')
        }
        return Promise.resolve()
      },
      trigger: 'change'
    }
  ]
}

// 注册状态
const registerLoading = ref(false)

// 获取验证码
const fetchCaptcha = async () => {
  try {
    const response = await getCaptcha()
    const responseData = response as any
  
    if (responseData.code === '00000') {
      captchaImage.value = responseData.data.base64Code
      formData.captchaKey = responseData.data.captchaKey
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    message.error('获取验证码失败')
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  fetchCaptcha()
}

// 处理注册
const handleRegister = async () => {
  try {
    await formRef.value?.validate()
    registerLoading.value = true
    
    // 调用注册API
    const result = await register({
      username: formData.username,
      phone: formData.phone,
      email: formData.email,
      password: formData.password,
      captcha: formData.captcha,
      captchaKey: formData.captchaKey
    })
    
    if ((result as any).code === '00000') {
      message.success('注册成功！请登录')
      emit('register-success', { username: formData.username })
      handleCancel()
      // 跳转到登录界面
      emit('show-login')
    } else {
      throw new Error((result as any).msg || '注册失败')
    }
    
  } catch (error: any) {
    if (error.errorFields) {
      // 表单验证错误，不需要处理
      return
    }
    message.error(error.message || '注册失败，请重试')
    // 注册失败时刷新验证码
    refreshCaptcha()
  } finally {
    registerLoading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  emit('update:open', false)
}

// 跳转到登录
const goToLogin = () => {
  emit('show-login')
}

// 表单引用
const formRef = ref()

// 组件挂载时获取验证码
onMounted(() => {
  fetchCaptcha()
})
</script>

<style scoped>
.register-container {
  padding: 20px 0;
}

.register-header {
  text-align: center;
  margin-bottom: 24px;
}

.register-header h1 {
  margin: 0 0 8px 0;
  color: #1890ff;
  font-size: 24px;
  font-weight: 600;
}

.register-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.register-form {
  margin-bottom: 24px;
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-image {
  width: 120px;
  height: 40px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  transition: all 0.3s;
}

.captcha-image:hover {
  border-color: #1890ff;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.captcha-placeholder {
  color: #999;
  font-size: 12px;
}

.register-btn {
  height: 40px;
  font-size: 16px;
  font-weight: 500;
}

.login-section {
  text-align: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.login-section span {
  color: #666;
  margin-right: 8px;
}

.agreement-link {
  padding: 0;
  height: auto;
  font-size: 14px;
}
</style>
